import logging

from fastapi.responses import JSONResponse

from app.models import create_response
from app.dependencies.redis import RedisDependency, RedisOperation

async def set_token(token,
                    user_id, 
                    message,
                    redis: RedisDependency):
    try:
        async with redis.pipeline() as pipe:
            pipe_operation = RedisOperation(pipe)
            await pipe_operation.item().set_value(user_id, token)
            result = await pipe.execute()
    except Exception as e:
        logging.error(f"redis error: {e}")
        return create_response(data={}, code=500, message="服务器内部错误")
    res = create_response(data={}, code=200, message=message)
    return JSONResponse(content=res, status_code=200, headers={"Authorization": f"{token}"})

async def delete_token(user_id, redis: RedisDependency):
    async with redis.pipeline() as pipe:
        try:
            pip_operation = RedisOperation(pipe)
            await pip_operation.item().delete_value(user_id)
            await pipe.execute()

        except Exception as e:
            return create_response(data={}, code=500, message="服务器内部错误")
        return create_response(data={}, code=200, message="退出成功")
